import router from '@/router/index'
import store from '@/store' // progress bar style
import { Toast } from 'vant'
import axios from 'axios'

axios.defaults.timeout = 30000 // 超时时间ms
axios.defaults.baseURL = 'http://114.115.213.140:88/RiskWarningSystem'

// 跨域请求，允许保存cookie
axios.defaults.withCredentials = false
// 是否正在刷新的标记
let isRefreshing = false
// 重试队列，每一项将是一个待执行的函数形式
let retryRequests = []

const err = error => {
  console.log('拦截错误===', error)
  const data = error.response.data
  const redata = {
    grant_type: 'refresh_token',
    refresh_token: localStorage.getItem('REFRESH_TOKEN')
  }
  if (error.response) {
    // 判断状态码
    if (error.response.status === 403) {
      Toast(data.message)
    } else if (error.response.status === 401) {
      localStorage.removeItem('ACCESS_TOKEN')
      if (!isRefreshing) {
        isRefreshing = true

        return store
          .dispatch('RefreshToken', redata)
          .then(res => {
            console.log(retryRequests.length)
            retryRequests.forEach(req => {
              req()
            })
            retryRequests = []
            return axios(error.response.config)
          })
          .catch(err => {
            console.log('err', err)
          })
      } else {
        return new Promise(resolve => {
          retryRequests.push(function() {
            resolve(axios(error.response.config))
          })
          console.log('+1')
        })
      }
    } else if (error.response.status === 422) {
      Toast(data.WorkOrder[0])
    }
  }
  return Promise.reject(error)
}

// HTTPrequest拦截
axios.interceptors.request.use(config => {
  // const token = localStorage.getItem('ACCESS_TOKEN')
  // if (token) {
  //   config.headers['Authorization'] = 'Bearer ' + token // 让每个请求携带自定义 token 请根据实际情况自行修改
  // }
  return config
})

// HTTP response拦截
axios.interceptors.response.use(response => {
  return response.data
})

export default axios
